﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KeRui.BLL;
using KeRui.Common;
using System.Text;
using System.Text.RegularExpressions;

public partial class Manage_Admin_RoleItem : System.Web.UI.Page
{
    protected int RoleID = PageRequest.GetInt("id", -1);
    public string Act = ManageHelper.PageAct();
    protected int OrderID = 0;
    protected List<KeRui.Model.AdminFlag> listAdminFlag;
    protected string[] sysRoles;
    protected List<KeRui.Model.CmsSite> listCmsSite;


    public string ActFlag = "addsave";
    public string ActName = "添加";
    protected KeRui.Model.AdminRole ModelAdminRole =new KeRui.Model.AdminRole();
    protected KeRui.BLL.AdminRole bllAdminRole = new AdminRole();
    protected KeRui.BLL.AdminFlag bllAdminFlag = new AdminFlag();
    protected KeRui.BLL.CmsSite bllCmsSite = new CmsSite();
    private ManageErrMsg nsb = new ManageErrMsg();
    protected void Page_Load(object sender, EventArgs e)
    {
        ManageHelper.CheckAdminLogin();//判断登录状态
        //系统权限列表

        listAdminFlag = bllAdminFlag.GetList(0, (int)ManageEnum.AdminFlagType.SystemFlag);
        //获取站点列表
        KeRui.BLL.CmsSite bllCmsSite = new CmsSite();
        listCmsSite = bllCmsSite.GetList();
        switch (Act)
        {
            case "addsave":
                Add();
                break;
            case "edit":
                Edit();
                break;
            case "editsave":
                EditSave();
                break;
            case "del":
                Del();
                break;
            case "showsite":
                ShowSite();
                break;
            default:
                break;
        }
    }

    #region 添加
    private void Add()
    {
        ManageHelper.CheckAdminPower("system_adminroleadd");//权限
        ModelAdminRole = new KeRui.Model.AdminRole();
        ModelAdminRole.RoleName = PageRequest.GetString("RoleName");
        ModelAdminRole.Note = PageRequest.GetString("Note");
        ModelAdminRole.OrderID = PageRequest.GetInt("OrderID", -1);
        #region ModelAdminRole.RoleFlag
        ModelAdminRole.RoleFlag = PageRequest.GetString("RoleFlag"); //获取系统权限
        string SiteRoleFlag = PageRequest.GetString("SiteRoleFlag");
        if (ModelAdminRole.RoleFlag != "")
        {
            if (SiteRoleFlag != "")
            {
                ModelAdminRole.RoleFlag = ModelAdminRole.RoleFlag + "," + SiteRoleFlag;
            }
        }
        else
        {
            ModelAdminRole.RoleFlag = SiteRoleFlag;
        }
        #endregion
        if (bllAdminRole.Add(ModelAdminRole) == 1)
        {
            Response.Write("<script type=\"text/javascript\">alert('已有相同名称的角色.');history.go(-1)</script>"); Response.End();
        }
        else
        {
            //Session.Remove("PermissionsKey");
            ManageHelper.AddLog("system_adminroleadd", "添加了“" + ModelAdminRole.RoleName + "”角色。");
            Response.Redirect("RoleItem.aspx?sucmsg=添加成功");
        }
    }
    #endregion

    #region 反显修改页面
    private void Edit()
    {
        ActFlag = "editsave";
        ActName = "修改";
        ModelAdminRole = bllAdminRole.GetModel(RoleID);
        if (ModelAdminRole == null)
        {
             nsb.AddErr("修改信息不存在。");
            nsb.ChkErr();
        }
    }
    #endregion

    #region 修改时保存
    private void EditSave()
    {
        ManageHelper.CheckAdminPower("system_adminroleedit");//权限
        KeRui.Model.AdminRole ModelAdminRole = new KeRui.Model.AdminRole();
        ModelAdminRole.RoleID = PageRequest.GetInt("RoleID", -1);
        if (ModelAdminRole.RoleID == -1)
        {
            nsb.AddErr("Error：RoleID没有得到。"); nsb.ChkErr();
        }
        ModelAdminRole.RoleName = PageRequest.GetString("RoleName");
        ModelAdminRole.Note = PageRequest.GetString("Note");
        ModelAdminRole.OrderID = PageRequest.GetInt("OrderID", -1);
        #region ModelAdminRole.RoleFlag 获取系统权限
        ModelAdminRole.RoleFlag = PageRequest.GetString("RoleFlag"); //获取系统权限
        string SiteRoleFlag = PageRequest.GetString("SiteRoleFlag");

        string[] listSiteRoleFlag = SiteRoleFlag.Split(',');

        string NewSiteFlag = "";
        for (int i = 0; i < listSiteRoleFlag.Length; i++)
        {
            if (listSiteRoleFlag[i] != "")
            {
                KeRui.Model.AdminRole modelAdminRole_old = new KeRui.Model.AdminRole();
                modelAdminRole_old = bllAdminRole.GetModel(ModelAdminRole.RoleID);
                if (modelAdminRole_old.RoleFlag.IndexOf(listSiteRoleFlag[i]) != -1)//原有数据中拥有该站点信息--则取出该站点的权限信息
                {
                    string pattern = @"site\w*?_" + listSiteRoleFlag[i].Replace("site_", "") + "";
                    Regex regex = new Regex(pattern);
                    MatchCollection collection = regex.Matches(modelAdminRole_old.RoleFlag);
                    foreach (Match match in collection)
                    {
                        NewSiteFlag += match.Captures[0].ToString() + ",";
                    }
                }
                else
                {
                    NewSiteFlag += listSiteRoleFlag[i] + ",";
                }
            }
        }
        if (NewSiteFlag !="")
            NewSiteFlag = NewSiteFlag.Substring(0, NewSiteFlag.Length - 1);
        if (ModelAdminRole.RoleFlag != "")
        {
            if (NewSiteFlag != "")
            {
                ModelAdminRole.RoleFlag = ModelAdminRole.RoleFlag + "," + NewSiteFlag;
            }
        }
        else
        {
            ModelAdminRole.RoleFlag = NewSiteFlag;
        }
        #endregion

        ModelAdminRole.UpdateTime = DateTime.Now;
        if (bllAdminRole.Update(ModelAdminRole) == 1)
        {
            nsb.AddErr("已有相同名称的角色。");
            nsb.ChkErr();
        }
        else
        {
            bllAdminRole.Update(ModelAdminRole);
            ManageHelper.AddLog("system_adminroleedit", "修改了“" + ModelAdminRole.RoleName + "”角色。");
            Response.Redirect("roleitem.aspx?sucmsg=修改成功&act=edit&id=" + ModelAdminRole.RoleID);
        }
    }
    #endregion

    #region 删除
    private void Del()
    {
        ManageHelper.CheckAdminPower("system_adminroledelete");//权限
        ModelAdminRole = bllAdminRole.GetModel(RoleID);
        if (ModelAdminRole == null)
        {
            Response.Write("该信息不存在。");
        }
        else
        {
            if (bllAdminRole.Delete(RoleID) == 1)
            {
                Response.Redirect("RoleList.aspx?errmsg=删除失败！该角色已被使用不能删除。");
            }
            else
            {
                ManageHelper.AddLog("system_adminroleedit", "删除了“" + ModelAdminRole.RoleName + "”角色。");
                Response.Redirect("RoleList.aspx?sucmsg=删除成功。");
            }
        }
    }
    #endregion

    #region 权限列表
    int EmptyNum = 0;
    protected string GetRoleFlagList(string strTmp)
    {
        strTmp = "," + strTmp + ",";
        StringBuilder xs = new StringBuilder();
        DataTable dt = bllAdminFlag.GetRoleChildFlag(0,0).Tables[0];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            EmptyNum = 0;
            string checkflag = "";
            if (strTmp.IndexOf("," + dt.Rows[i][4].ToString() + ",") != -1)
            {
                checkflag = "checked";
            }
            xs.AppendFormat("<div id=\"p{0}\"><ul class=\"ultitle\" id=\"t{0}\"><input type=\"checkbox\" name=\"RoleFlag\" id=\"{0}\"  value=\"{3}\" " + checkflag + " onclick=\"selAll(this.id)\">" +
                "<img align=\"absmiddle\" src=\"/Manage/pic/menu/{2}\"/>&nbsp;<span id=\"s{0}\"onclick=\"showchildnode(this.id)\" style=\"cursor:pointer;\">{1}</span></ul>",
                dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString());
            xs.Append(GetChildRoleFlagList(Convert.ToInt32(dt.Rows[i][0]), strTmp));
            xs.Append("</div>");
        }
        return xs.ToString();
    }
    private string GetChildRoleFlagList(int pID, string strTmp)
    {
        strTmp = "," + strTmp + ",";
        string xs = "";
        for (int n = 0; n < EmptyNum; n++)
        {
            xs += "　";
        }
        StringBuilder strRFlaglist = new StringBuilder();
        if (EmptyNum == 0)
        {
            strRFlaglist.Append("<ul class=\"divurl\" id=\"c" + pID + "\" style=\"border:1px solid #99CCFF;\">");
        }
        else
        {
            strRFlaglist.Append("<ul class=\"divurl\" id=\"c" + pID + "\">");
        }
        DataTable dtChild = bllAdminFlag.GetRoleChildFlag(pID,0).Tables[0];
        for (int m = 0; m < dtChild.Rows.Count; m++)
        {
            string checkflag = "";
            if (strTmp.IndexOf("," + dtChild.Rows[m][4].ToString() + ",") != -1)
            {
                checkflag = "checked";
            }
            strRFlaglist.AppendFormat("<li>" + xs + "<input type=\"checkbox\"  name=\"RoleFlag\" id=\"{0}\" value=\"{3}\" " + checkflag + " onclick=\"conclick(this.id," + pID + ")\">" +
                "<img align=\"absmiddle\" src=\"/Manage/pic/menu/{2}\"/>&nbsp;{1}</li>", dtChild.Rows[m][0].ToString(), dtChild.Rows[m][1].ToString(),
                dtChild.Rows[m][3].ToString().ToLower() == "" ? "item.gif" : dtChild.Rows[m][3].ToString(), dtChild.Rows[m][4].ToString());
            if (dtChild.Rows[m]["HaveChildNav"].ToString().ToLower() == "true")
            {
                EmptyNum++;
                strRFlaglist.Append(GetChildRoleFlagList(Convert.ToInt32(dtChild.Rows[m][0]), strTmp));
            }
        }
        strRFlaglist.Append("</ul>");
        return strRFlaglist.ToString();
    }
    #endregion

    #region 显示可以管理的站点 ajax
    private void ShowSite()
    {
        string StrRet = "";
        int RoleID = PageRequest.GetInt("id", -1);
        ModelAdminRole = bllAdminRole.GetModel(RoleID);
        if (ModelAdminRole == null)
        {
            Response.Write("Error"); Response.End();
        }
        CmsSite bllCmsSite = new CmsSite();
        List<KeRui.Model.CmsSite> list = bllCmsSite.GetList();
        string RoleFlag=","+ModelAdminRole.RoleFlag+",";
        foreach (KeRui.Model.CmsSite model in list)
        {
            if (RoleFlag.IndexOf(",site_" + model.SiteID+ ",")!=-1)
            {
                StrRet += "<li><a href=\"SiteRole.aspx?siteid=" + model.SiteID + "&roleid=" + RoleID + "\">" + model.SiteName + "</a></li>";
            }
        }
        if (StrRet == "")
        {
            StrRet = "没有分配站点。";
        }
        Response.Write(StrRet); Response.End();

    }
    #endregion
}
